#!/usr/bin/env python
#-*-encoding:utf-8-*-
'''
Created on 2015年3月31日

@author: chenyongbing
'''
import sys,os
#current_dir = os.path.dirname(__file__)
current_dir = os.path.split(os.path.realpath(__file__))[0]


from retail_datas import myRetail
import logging
class FormDatas():
    def __init__(self):
        pass
    def get_companies_data(self,tab='companies',cate=None,prov=None,city=None,dist=None):
        datas = []
        query = 'select id,name from %s'%tab
        if prov!=None:
            company_ids = self.get_companies_by_region(prov=prov, city=city, dist=dist)
        else:
            company_ids=[]
        if cate!=None:
            query = query + ' where company_type="%s"'%(cate)
        
        if cate!=None and len(company_ids)!=0:
            company_str = myRetail.conv_tuple_to_str(company_ids)
            
            query = query + ' and id in (%s)'%company_str
        elif len(company_ids)!=0:
            company_str = myRetail.conv_tuple_to_str(company_ids)
            query = query + ' where id in (%s)'%company_str 
        query+= ' order by name'  
        logging.debug(query)
        rets = myRetail.SelectAll(query)
        if rets==None:rets=[]
        logging.info('found %s companies.'%len(rets))
        for id,name in rets:
            datas.append([int(id),name])
        return datas
    def get_cates_data(self,tab='companies',prov=None,city=None,dist=None,comp_id=None):
        query = 'select distinct company_type from %s'%tab
        
        if comp_id!=None:
            query = query + ' where id="%s"'%comp_id 
        else:
            if prov!=None:
                company_ids = self.get_companies_by_region(prov=prov, city=city, dist=dist)
            else:
                company_ids=[]
            if len(company_ids)!=0:
                company_str = myRetail.conv_tuple_to_str(company_ids)
                query = query + ' where id in (%s)'%company_str   
        logging.debug(query)
        rets = myRetail.SelectAll(query)
        if rets==None:rets=()
        logging.info('found %s cates.'%len(rets))
        datas = []
        i=0
        for ret in rets:
            company_type = ret[0]
            if company_type=='':continue
            i+=1
            datas.append([company_type,company_type])
        return datas
    
    def get_region_data(self,cate=None,comp_id=None,prov=None,city=None):
        if prov==None and city==None:
            query = 'select distinct province from groups'
        elif city==None:
            query = 'select distinct city from groups where province="%s"'%(prov)
        else:
            query = 'select distinct distribution from groups where province="%s" and city="%s"'%(prov,city)
        company_ids = []
        if comp_id!=None and prov==None and city==None :
            query = query +' where company_id="%s"'%comp_id
        elif comp_id!=None:
            query = query +' and company_id="%s"'%comp_id
        else:
            if cate!=None and prov==None and city==None :
                company_ids = self.get_companies_by_cate(cate)
                company_str = myRetail.conv_tuple_to_str(company_ids)
                
                query = query + ' where company_id in (%s)'%company_str
            elif cate!=None:
                company_ids = self.get_companies_by_cate(cate)
                company_str = myRetail.conv_tuple_to_str(company_ids)
                query = query + ' and company_id in (%s)'%company_str
        logging.debug(query)
        
        rets = myRetail.SelectAll(query)
        if rets==None:rets=()
        datas = []
        i=0
        for ret in rets:
            region = ret[0]
            if region=='' or region==None:continue
            i+=1
            datas.append([region,region])
        logging.info('found %s regions.'%(len(datas)))
        return datas
    
    
    

    
    def get_groups_data(self,comp_id=None,prov=None,city=None,dist=None,cate=None,shop_group=None):
        query = 'select id , name from groups where type=4'
        if shop_group!=None:
            query = query + ' and id="%s"'%shop_group
        else:
            if comp_id!=None:
                query = query + ' and company_id="%s"'%comp_id
            elif cate!=None:
                company_ids = self.get_companies_by_cate(cate)
                company_str = myRetail.conv_tuple_to_str(company_ids)
                query = query + ' and company_id in (%s)'%company_str
            if prov!=None:
                query = query + ' and province="%s"'%prov
            if city!=None:
                query = query + ' and city="%s"'%city
            if dist!=None:
                query = query + ' and distribution="%s"'%dist
        query += ' and deleted!=1'
        query += ' order by name'
        logging.debug(query)
        rets = myRetail.SelectAll(query)
        if rets==None:rets=()
        datas = []
        for group_id,group_name in rets:
            datas.append([int(group_id),group_name])
        logging.info('found %s groups.'%(len(datas)))
        return datas
        
    
            
    
    def get_companies_by_cate(self,cate=None):
        datas = []
        query = 'select id from companies'
        if cate!=None:
            query = query + ' where company_type="%s"'%cate
        logging.debug(query)
        rets = myRetail.SelectAll(query)
        
        company_ids= []
        for ret in rets:
            company_ids.append(int(ret[0]))
        logging.info('found %s company ids.'%len(company_ids))
        return company_ids
    def get_companies_by_region(self,prov=None,city=None,dist=None):
        datas = []
        query = 'select distinct company_id from groups'
        if prov!=None and city!=None and dist!=None:
            query =query+ ' where province="%s" and city="%s" and distribution="%s"'%(prov,city,dist)
        elif prov!=None and city!=None:
            query =query+ ' where province="%s" and city="%s"'%(prov,city)
        elif prov!=None:
            query =query+ ' where province="%s"'%(prov)
        logging.debug(query)
        rets = myRetail.SelectAll(query)
        company_ids= []
        for ret in rets:
            company_ids.append(int(ret[0]))
        logging.info('')
        return company_ids
        
    def export_base_feild_form(self,request,myForm,initial):
        #myForm.initial= initial
        if initial.has_key('province'):
            prov = initial['province']
        else:
            prov = None
        if initial.has_key('city'):
            city = initial['city']
        else:
            city = None
        
        if initial.has_key('dist'):
            dist = initial['dist']
        else:
            dist = None
        
        if initial.has_key('cate'):
            cate = initial['cate']
        else:
            cate = None
            
        if initial.has_key('company'):
            comp_id = initial['company']
        else:
            comp_id = None
        if initial.has_key('group'):
            group = initial['group']
        else:
            group = None
        
        if prov=='province':prov = None
        if cate == 'cate':cate= None
        if comp_id=='company':comp_id=None
        if city == 'city':city = None
        if dist == 'dist':dist=None
        if group == 'group':group = None
        #[['company','请选择公司']]+
        companies = self.get_companies_data(cate=cate, prov=prov, city=city, 
     dist=None)
        
        #groups = [['group','请选择门店']] 
        if comp_id!=None or prov!=None:
            groups =   self.get_groups_data(comp_id=comp_id, prov=prov, city=city, dist=dist)
        else:
            groups = []
        #[['cate','请选择类别']]+
        if 'cate' in initial.keys():
            cates = self.get_cates_data(prov=prov, city=city, dist=dist,comp_id=comp_id)
            myForm.fields['cate'].choices +=cates
        #[['province','请选择省份']]+
        if 'provinces' in initial.keys():
            provinces =  self.get_region_data(cate=cate, comp_id=comp_id)
            myForm.fields['province'].choices +=provinces
        if 'city' in initial.keys():
            cities = [['city','请选择城市']]
            if prov!=None and prov!='province':
                 cities =  self.get_region_data(cate=cate, comp_id=comp_id, prov=prov)
            else:
                cities = []
            myForm.fields['city'].choices +=cities
        #dists = [['dist','请选择区域']]
        if 'dist' in initial.keys():
            if city!=None and city!='city':
                dists =  self.get_region_data(cate=cate, comp_id=comp_id, prov=prov, city=city)
            else:
                dists = []
            myForm.fields['dist'].choices +=dists
        #myForm.initial({'company':companies,'cates':cates,'province':provinces})
        
        myForm.fields['company'].choices +=companies

        myForm.fields['group'].choices +=groups
        return myForm
            
        
myFormDatas = FormDatas()   
    
    